const Koa = require("koa");
const router = require("koa-router")();
const koaBody = require("koa-body");
const cors = require("@koa/cors");
const compress = require("koa-compress")
const fs = require('fs');
const DB = require("./module/db");
const admin = require("./routes/admin");
const index = require("./routes");
const user = require("./routes/cgpcp/user");
const atlas = require("./routes/atlas");
const picture = require("./routes/cgpcp/media/picture");
const comment = require("./routes/cgpcp/comment");
const tagging = require("./routes/cgpcp/tagging");
const media = require("./routes/cgpcp/media");
const review = require("./routes/cgpcp/review");
const project = require("./routes/cgpcp/project");
const login = require("./routes/cgyunLogin");
const collection = require("./routes/cgpcp/collection")
const task = require("./routes/task")
const cgTask = require("./routes/cgclass/task")

const app = new Koa();

app.use(koaBody({
    multipart: true,
    formidable: {
        maxFileSize: 200*1024*1024    // 设置上传文件大小最大限制，默认2M
    }}))
    .use(cors())
    .use(compress({
        filter (content_type) { // 只有在请求的content-type中有gzip类型，我们才会考虑压缩，因为zlib是压缩成gzip类型的
            return /text/i.test(content_type);
        },
        threshold: 2048, // 阀值，当数据超过2kb的时候，可以压缩
        flush: require('zlib').Z_SYNC_FLUSH, // zlib是node的压缩模块
    }));

//配置模板引擎
router.get("/api", async (ctx) => {
    var result = await DB.find('user', {});
    ctx.body = {
        result
    }

}).get("/add", async (ctx) => {
    let data = await DB.insert('user', {'username': '王八', 'age': 88, 'sex': 'female', 'status': '0'});
    console.log(data.result);   //1为增加成功
    ctx.body = "新闻页面";
    await ctx.render('add');

}).get("/api/test", async (ctx) => {
    // ctx.redirect('https://www.baidu.com/')
    ctx.body = "连接上啦!";
    console.log(ctx.query['user'])
    // ctx.redirect('/api')

}).get("/test", async (ctx) => {
    const readfilePromise = new Promise((resolve, reject) => {
        fs.readFile('/home/jingze/test-90MB', function(err, data){
            if (err)
                return reject(err);
            resolve(data)
        })
    });
    await readfilePromise.then(data => ctx.body = data, err => console.log(err));

}).get("/edit", async (ctx) => {
    //获取用户信息,id
    let id = ctx.query.id;
    let data = await DB.find('user', {"_id": DB.getObjectId(id)});
    console.log(data);
    await ctx.render('edit', {
        list: data[0]
    });

}).get("/delete", async (ctx) => {
    let id = ctx.query.id;
    let data = await DB.remove1('user', {"_id": DB.getObjectId(id)});
    if (data.result.ok) {
        ctx.redirect('/');
    }

}).post("/doAdd", async (ctx) => {
    console.log(ctx.request.body)
    // let data = await DB.insert('user', ctx.request.body);
    // try {
    //     if (data.result.ok) {
    //         ctx.redirect('/');
    //     }
    // } catch (e) {
    //     console.log(e);
    //     ctx.redirect('/add');
    // }

}).post("/doEdit", async (ctx) => {
    var id = ctx.request.body.id;
    var username = ctx.request.body.username;
    var age = ctx.request.body.age;
    var sex = ctx.request.body.sex;
    let data = await DB.update('user', {"_id": DB.getObjectId(id)}, {
        username, age, sex
    });
    try {
        if (data.result.ok) {
            ctx.redirect('/');
        }
    } catch (e) {
        console.log(e);
        ctx.redirect('/edit');
    }

}).use('/api/admin', admin)
    .use('/api/user', user)
    .use('/api/atlas', atlas)
    .use('/api/comment', comment)
    .use('/api/picture', picture)
    .use('/api/tagging', tagging)
    .use('/api/media', media)
    .use('/api/review', review)
    .use('/api/project', project)
    .use('/api/collection', collection)
    .use('/api/task', task)
    .use('/api/login', login)
    .use('/api/cgTask', cgTask)
    .use('/api/index', index);  //配置子路由


//启动路由
app
    .use(router.routes())
    .use(router.allowedMethods())

app.listen(3000);
console.log("node is listening 3000");
